# 将获取好的音频文件包装成 dataloader的形式
import os
import random
import shutil


# 0 将数据集进行分好类
# 标签1 3500个正例   3500个反例（2000个无鼾声 1500个有鼾声）
files_path = "E:\\data\\鼾声多模态\\止鼾枕清洗后的数据2"
# 首先截取3500个正例
files_label_1_path = os.path.join(files_path, "1")
files_label_0_path = os.path.join(files_path, "0")

files_positive_list = os.listdir(files_label_1_path)
files_negitive_list = os.listdir(files_label_0_path)
# print(files_negitive_list[:10])

def pairTxtWav(files_list, number):
    # 使用集合记录 .txt 和 .wav 的文件编号
    txt_files = set()
    wav_files = set()
    for file in files_list:
        name, ext = os.path.splitext(file)
        if ext == ".txt":
            txt_files.add(name)
        elif ext == ".wav":
            wav_files.add(name)

    # 找到既有 .txt 又有 .wav 的文件编号
    common_files = sorted(txt_files & wav_files)[:number]  # 每个编号配对两文件，取前 10 个文件需要取 5 对

    # 生成结果列表
    result  = []
    for name in common_files:
        result.append(f"{name}.txt")
        result.append(f"{name}.wav")
    return result


filter_positive_list = pairTxtWav(files_positive_list, 3500)
filter_negitive_list = pairTxtWav(files_negitive_list, 2000)
# print(filter_negitive_list[:10])

def choose_files(files_list, ext:str, number):
    # 筛选出所有 .wav 文件
    wav_files = [file for file in files_list if file.endswith(ext)]

    # 随机选取前number个 .wav 文件
    result = random.sample(wav_files, min(len(wav_files), number))
    return result

# 获取有鼾声的1500例子
filter_negitive_wav_list = choose_files(files_positive_list, ".wav", 1500)
filter_negitive_txt_list = choose_files(filter_negitive_list, ".txt", 1500)
# print(filter_negitive_wav_list[:10])
# 转移文件
destination_folder = "E:\\data\\鼾声多模态\\止鼾枕清洗后的数据3"  # 替换为实际的目标文件夹路径

# 确保目标文件夹存在
os.makedirs(destination_folder, exist_ok=True)

# 移动文件到目标文件夹
# for file in filter_negitive_list:
#     source_path = os.path.join(files_path, "0", file)
#     destination_path = os.path.join(destination_folder, "0",file)
#     shutil.copy2(source_path, destination_path)

print(f"All files moved to {destination_folder}")

# 获取1500个反例
# 遍历 txt 和 wav 文件，复制并重命名 txt 文件
for txt_file, wav_file in zip(filter_negitive_txt_list, filter_negitive_wav_list):
    # 获取完整路径
    txt_source_path = os.path.join(files_path, "0", txt_file)
    wav_source_path = os.path.join(files_path, "1", wav_file)
    
    # 目标路径（将 txt 文件名修改为对应的 wav 文件名，但扩展名保持为 .txt）
    new_txt_file = wav_file.replace(".wav", ".txt") 
    txt_destination_path = os.path.join(destination_folder, "0", new_txt_file)
    wav_destination_path = os.path.join(destination_folder, "0", wav_file)

    # 确保目标文件夹内的子文件夹 "0" 存在
    os.makedirs(os.path.join(destination_folder, "0"), exist_ok=True)

    # 复制文件
    shutil.copy2(txt_source_path, txt_destination_path)  # 复制 .txt 文件并改名
    shutil.copy2(wav_source_path, wav_destination_path)  # 复制 .wav 文件

# 划分训练集和测试集


# 1 重新修改 鼾声代码

# 2 进行训练
